<?php

namespace Restaurant\Controller;


use Core\Config;
use Core\Controller\RestaurantAdminBaseController;
use Core\Exception\BusinessException;
use Core\Helper\CommonHelper;
use Core\Session\FrontSessionHelper;
use Exception;
use Zend\View\Model\JsonModel;

class CatalogController extends RestaurantAdminBaseController {
    public function indexAction() {
        $this->initPageWithLayout();
        return $this->getViewModel();
    }

    public function categoryAction() {
        $this->initPageWithLayout();
        $categoryCode = $this->params()->fromQuery('code');
        $categoryTable = $this->getResTableFinder()->getCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $category = $categoryTable->getCategoryByCode($categoryCode);
        $this->getViewModel()->setVariable('categoryItem', $category);
        return $this->getViewModel();
    }


    public function getCategoryGroupContentAction(){
        $viewModel = $this->getViewModel();
        $viewModel->setTerminal(true);
        $groupCode = $this->params()->fromPost('groupCode');
        $domain = $this->params()->fromRoute('domain');
        $viewModel->setVariable('groupCode', $groupCode);

        $categoryTable = $this->getResTableFinder()->getCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $categoryAsKendoDataSourceArr = $categoryTable->getCategoryAsKendoDataSource($groupCode);
        $viewModel->setVariable('categoryAsKendoDataSourceArr',$categoryAsKendoDataSourceArr);

        $rootCategory = $categoryTable->getRootCategory($groupCode);
        $viewModel->setVariable('rootCategory',$rootCategory);
        return $viewModel;
    }

    public function getCategoryParentAction(){
        try{

            $id = $this->params()->fromPost('id');
            $domain = $this->domainCode;
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($id);
            $category_Item->setDomain($domain);
            $directParent = $category_Item->getDirectParent();
            if(!$directParent)
                return new JsonModel(array('success'=>true, "upable"=>false, "downable"=>false));
            else{
                $upable = true;
                $downable = true;

                if($directParent->lft == $category_Item->lft - 1 )
                    $upable = false;
                if($directParent->rgt == $category_Item->rgt + 1 )
                    $downable = false;
                return new JsonModel(array('success'=>true, "upable"=>$upable, "downable"=>$downable));
            }

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    private function validateSaveCategory($allParams){
        if(!$allParams['code'] ||!$allParams['name'])
            throw new BusinessException('Vui lòng nhập đầy đủ thông tin bắt buộc');

        $categoryTable = $this->getResTableFinder()->getCategoryTable(
            FrontSessionHelper::getCurrentLang());

        if(!$allParams['id']){
            $category_Item = $categoryTable->getCategory($allParams['parentId']);
            $sameCodeCategory = $categoryTable->getCategoryByCodeInGroup(
                $category_Item->group_code, $allParams['code']);
            if($sameCodeCategory)
                throw new BusinessException('Đã tồn tại nhóm có mã: '.$allParams['code']);
        }else{
            $category_Item = $categoryTable->getCategory($allParams['id']);
            $sameCodeCategory = $categoryTable->getCategoryByCodeInGroup(
                $category_Item->group_code, $allParams['code']);
            if($sameCodeCategory && $sameCodeCategory->id != $allParams['id'])
                throw new BusinessException('Đã tồn tại nhóm có mã: '.$allParams['code']);
        }
    }

    public function saveCategoryAction(){
        try{
            $this->validateSaveCategory($this->params()->fromPost()) ;
            $code = $this->params()->fromPost('code');
            $name = $this->params()->fromPost('name');
            $description = $this->params()->fromPost('description');
            $parentId = $this->params()->fromPost('parentId');

            $id = $this->params()->fromPost('id');

            $categoryTable = $this->getResTableFinder()->getCategoryTable(
                FrontSessionHelper::getCurrentLang());

            if(!$id){
                $data = array("code"=>$code,"name"=>$name,"description"=>$description,"parentId"=>$parentId);
                $id = $categoryTable->addCategory($data);
            }
            else{
                $data = array("id"=>$id, "code"=>$code,"name"=>$name,"description"=>$description);
                $categoryTable->updateCategory($data);
            }

            return new JsonModel(array('success'=>true,'id'=>$id));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function upCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($id);
            $category_Item->setDomain($this->domainCode);
            $category_Item->upMyPosition();
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function downCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($id);
            $category_Item->setDomain($this->domainCode);
            $category_Item->downMyPosition();
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function removeCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $categoryTable->removeCategory($id);
            return new JsonModel(array('success'=>true));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }
    public function categoryListAction(){
        try{

            $categoryId = $this->params()->fromPost('id');
            $categoryTable = $this->getResTableFinder()->getCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($categoryId);
            $categoryAsKendoDataSourceArr = $categoryTable->getCategoryAsKendoDataSource($category_Item->group_code);
            return new JsonModel($categoryAsKendoDataSourceArr);
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    //==================quan ly don vi thuc don======================

    public function unitAction() {
        $this->initPageWithLayout();
        $unitTable = $this->getResTableFinder()->
            getUnitTable(FrontSessionHelper::getCurrentLang());
        $this->getViewModel()->setVariable('allUnits', $unitTable->getAllAsArray());
        return $this->getViewModel();
    }

    public function saveUnitAction(){
        try{

            $id = $this->params()->fromPost('id');
            $name = $this->params()->fromPost('name');
            $unitTable = $this->getResTableFinder()->getUnitTable(
                FrontSessionHelper::getCurrentLang());
            if(!$id)
                $id = $unitTable->addUnit(array('name'=>$name));
            else
                $unitTable->updateUnit(array('name'=>$name, 'id'=>$id));

            return new JsonModel(array('success'=>true, 'data'=>array('id'=>$id, 'name'=>$name)));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function deleteUnitAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id) throw new BusinessException('Chưa truyền id!');
            $unitTable = $this->getResTableFinder()->getUnitTable(
                FrontSessionHelper::getCurrentLang());

            $unitTable->deleteUnit(array('id'=>$id));

            return new JsonModel(array('success'=>true));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function getUnitDefaultNameAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id) throw new BusinessException('Chưa truyền id!');

            $unitLangTable = $this->getResTableFinder()->getUnitLangTable();
            $unitLang = $unitLangTable->getByUnitAndLang($id, Config::getDefaultLanguage());

            return new JsonModel(array('success'=>true, 'value'=>$unitLang->name));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }


//==================== multiple language category =======================
    public function mlCategoryAction() {
        $this->initPageWithLayout();
        $categoryCode = $this->params()->fromQuery('code');
        $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $category = $categoryTable->getMlCategoryByCode($categoryCode);
        $this->getViewModel()->setVariable('categoryItem', $category);
        return $this->getViewModel();
    }

    public function getMlCategoryGroupContentAction(){
        $viewModel = $this->getViewModel();
        $viewModel->setTerminal(true);
        $groupCode = $this->params()->fromPost('groupCode');
        $viewModel->setVariable('groupCode', $groupCode);

        $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $categoryAsKendoDataSourceArr = $categoryTable->getMlCategoryAsKendoDataSource($groupCode);
        $viewModel->setVariable('categoryAsKendoDataSourceArr',$categoryAsKendoDataSourceArr);

        $rootCategory = $categoryTable->getRootMlCategory($groupCode);
        $viewModel->setVariable('rootCategory',$rootCategory);
        return $viewModel;
    }

    private function validateSaveMlCategory($allParams){
        if(!$allParams['code'] ||!$allParams['name'])
            throw new BusinessException('Vui lòng nhập đầy đủ thông tin bắt buộc');

        $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
            FrontSessionHelper::getCurrentLang());

        if(!$allParams['id']){
            $category_Item = $categoryTable->getMlCategory($allParams['parentId']);
            $sameCodeCategory = $categoryTable->getMlCategoryByCodeInGroup(
                $category_Item->group_code, $allParams['code']);
            if($sameCodeCategory)
                throw new BusinessException('Đã tồn tại nhóm có mã: '.$allParams['code']);

            $sameAliasCategory = $categoryTable->getMlCategoryByAliasInGroup(
                $category_Item->group_code, CommonHelper::vietnameseToASCII($allParams['name']));
            if($sameAliasCategory)
                throw new BusinessException('Đã tồn tại nhóm có tên: '.$allParams['name']);

        }else{
            $category_Item = $categoryTable->getMlCategory($allParams['id']);
            $sameCodeCategory = $categoryTable->getMlCategoryByCodeInGroup(
                $category_Item->group_code, $allParams['code']);
            if($sameCodeCategory && $sameCodeCategory->id != $allParams['id'])
                throw new BusinessException('Đã tồn tại nhóm có mã: '.$allParams['code']);

            $sameAliasCategory = $categoryTable->getMlCategoryByAliasInGroup(
                $category_Item->group_code, CommonHelper::vietnameseToASCII($allParams['name']));
            if($sameAliasCategory&& $sameAliasCategory->id != $allParams['id'])
                throw new BusinessException('Đã tồn tại nhóm có tên: '.$allParams['name']);
        }
    }

    public function saveMlCategoryAction(){
        try{
            $this->validateSaveMlCategory($this->params()->fromPost()) ;
            $code = $this->params()->fromPost('code');
            $name = $this->params()->fromPost('name');
            $description = $this->params()->fromPost('description');
            $parentId = $this->params()->fromPost('parentId');

            $id = $this->params()->fromPost('id');

            $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
                FrontSessionHelper::getCurrentLang());

            if(!$id){
                $data = array("code"=>$code,"name"=>$name,"description"=>$description,"parentId"=>$parentId);
                $id = $categoryTable->addMlCategory($data);
            }
            else{
                $data = array("id"=>$id, "code"=>$code,"name"=>$name,"description"=>$description);
                $categoryTable->updateMlCategory($data);
            }

            return new JsonModel(array('success'=>true,'id'=>$id));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function getMlCategoryParentAction(){
        try{

            $id = $this->params()->fromPost('id');
            $domain = $this->domainCode;
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getMlCategory($id);
            $category_Item->setDomain($domain);
            $directParent = $category_Item->getDirectParent();
            if(!$directParent)
                return new JsonModel(array('success'=>true, "upable"=>false, "downable"=>false));
            else{
                $upable = true;
                $downable = true;

                if($directParent->lft == $category_Item->lft - 1 )
                    $upable = false;
                if($directParent->rgt == $category_Item->rgt + 1 )
                    $downable = false;
                return new JsonModel(array('success'=>true, "upable"=>$upable, "downable"=>$downable));
            }

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function upMlCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getMlCategory($id);
            $category_Item->setDomain($this->domainCode);
            $category_Item->upMyPosition();
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function downMlCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getMlCategory($id);
            $category_Item->setDomain($this->domainCode);
            $category_Item->downMyPosition();
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function removeMlCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $categoryTable->removeMlCategory($id);
            return new JsonModel(array('success'=>true));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }
    public function categoryMlListAction(){
        try{

            $categoryId = $this->params()->fromPost('id');
            $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getMlCategory($categoryId);
            $categoryAsKendoDataSourceArr = $categoryTable->getMlCategoryAsKendoDataSource($category_Item->group_code);
            return new JsonModel($categoryAsKendoDataSourceArr);
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function getDefaultMlCategoryLangAction(){
        try{

            $categoryId = $this->params()->fromPost('id');
            $categoryTable = $this->getResTableFinder()->getMlCategoryTable(
                FrontSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getMlCategory($categoryId);
            $mlCategoryLang = $category_Item->getMlCategoryLang(Config::getDefaultLanguage());
            return new JsonModel(array('success'=>true, 'name'=>$mlCategoryLang->name,
                'description'=>$mlCategoryLang->description));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }


}